#!/bin/bash
#
# Copyright 2015-2017 Adrian DC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# === Uploads Credentials for FTP ===
function __shtools_credentials_ftp()
{
  # Usage: __shtools_credentials_ftp [uploadftp_variant] (Credentials for FTP server)

  # FTP Uploads Credentials
  export FTPUploadUserUrl='ftp.domain.universe';
  export FTPUploadUserName='Username';
  export FTPUploadPassword=;
  export FTPUploadPath=;

  # Create  .bash_android.uploadftp.**name**.rc with the exports to override the credentials
  if [ ! -z "${1}" ] && [ -f "${ANDROID_DEVELOPMENT_SHELL_TOOLS_WORKSPACE:-${HOME}}/.bash_android.uploadftp.${1}.rc" ]; then
    source "${ANDROID_DEVELOPMENT_SHELL_TOOLS_WORKSPACE:-${HOME}}/.bash_android.uploadftp.${1}.rc";
  elif [ -f "${ANDROID_DEVELOPMENT_SHELL_TOOLS_WORKSPACE:-${HOME}}/.bash_android.uploadftp.main.rc" ]; then
    source "${ANDROID_DEVELOPMENT_SHELL_TOOLS_WORKSPACE:-${HOME}}/.bash_android.uploadftp.main.rc";
  fi;

  # Check missing credentials
  [ ! "${FTPUploadUserUrl}" = 'ftp.domain.universe' ];
}

# === File Uploader FTP ===
function uploadftp()
{
  # Usage
  if [ -z "${1}" ]; then
    echo '';
    echo ' Usage: uploadftp <file_path> [target_folder] [uploadftp_variant] (File to FTP server uploader)';
    echo '';
    return;
  fi;

  # Variables
  local send_file=${1};
  local upload_folder=${2:-Development};
  local variant=${3};
  local send_file_ext;
  local send_file_name;
  local time_start;
  local time_span;

  # Initialize variables
  time_start=$(date +%s);

  # FTP Uploads Credentials
  if ! __shtools_credentials_ftp "${variant}"; then
    >&2 echo '';
    >&2 echo ' uploadftp: Open android_uploads_ftp.rc to see how to set your logins';
    >&2 echo '';
    return;
  fi;

  # Upload header
  echo '';
  echo -e " \e[1;33m[ Uploading to the server - User '${FTPUploadUserName}' - Path '${upload_folder}' ]\e[0m";
  echo '';

  # Upload file to target
  if [ ! -z "${send_file}" ] && [ -f "${send_file}" ]; then

    # File variables
    send_file_name=$(basename "${send_file}");
    send_file_ext=${send_file_ext##*.};

    # Path prepend
    if [ ! -z "${FTPUploadPath}" ] && [ ! -z "${upload_folder}" ]; then
      upload_folder=${FTPUploadPath}/${upload_folder};
    fi;

    # Notify the file name
    echo "   File '${send_file_name}' uploading...";
    echo '';

    # Upload through FTP
    if ! ncftpput \
        -m \
        -v \
        -t 10 \
        -u "${FTPUploadUserName}" \
        -p "${FTPUploadPassword}" \
        "${FTPUploadUserUrl}" \
        "${upload_folder}" \
        "${send_file}"; then

      # Failed FTP upload
      notify-send 'Failed uploading through FTP...' 2> /dev/null;
      echo '';
      echo '   Failed uploading through FTP.';
    fi;

  # File missing
  else
    echo "  File '${send_file}' not found...";
  fi;

  # Show upload time
  time_span=$(($(date +%s) - time_start));
  echo '';
  echo -e " \e[1;37m[ Upload done in ${time_span} secs ]\e[0m";
  echo '';
}

# === File Downloader FTP ===
function downloadftp()
{
  # Usage
  if [ -z "${1}" ]; then
    echo '';
    echo ' Usage: downloadftp <remote_path> [uploadftp_variant] (Download from FTP)';
    echo '';
    return;
  fi;

  # Variables
  local download_file=${1};
  local variant=${2};
  local download_file_name;
  local time_start;
  local time_span;

  # Initialize variables
  download_file_name=$(basename "${download_file}");
  time_start=$(date +%s);

  # FTP Uploads Credentials
  if ! __shtools_credentials_ftp "${variant}"; then
    >&2 echo '';
    >&2 echo ' downloadftp: Open android_uploads_ftp.rc to see how to set your logins';
    >&2 echo '';
    return;
  fi;

  # Download header
  echo '';
  echo -e " \e[1;33m[ Downloading from the server - User '${FTPUploadUserName}' ]\e[0m";
  echo '';

  # Path prepend
  if [ ! -z "${FTPUploadPath}" ]; then
    download_file=${FTPUploadPath}/${download_file};
  fi;

  # Notify the file name
  echo "   File '${download_file}' downloading...";
  echo '';

  # Upload through FTP
  ncftpget -C \
           -v \
           -t 10 \
           -u "${FTPUploadUserName}" \
           -p "${FTPUploadPassword}" \
           "${FTPUploadUserUrl}" \
           "${download_file}" \
           "./${download_file_name}";

  # Detect result FTP download
  case ${?} in
    0) ;;
    3) echo '   Local file is identical to remote file.';
       ;;
    *) notify-send 'Failed downloading through FTP...' 2> /dev/null;
       echo '';
       echo '   Failed downloading through FTP.';
       ;;
  esac;

  # Show download time
  time_span=$(($(date +%s) - time_start));
  echo '';
  echo -e " \e[1;37m[ Download done in ${time_span} secs ]\e[0m";
  echo '';
}

# === Folder Syncer FTP ===
function syncftp()
{
  # Usage
  if [ -z "${1}" ] || [ -z "${3}" ]; then
    echo '';
    echo ' Usage: syncftp <local_path> <remote_path> <--download/--upload> [uploadftp_variant] (Folder with FTP server syncer)';
    echo '';
    return;
  fi;

  # Variables
  local remote_path=${2};
  local mode=${3};
  local variant=${4};
  local local_path;
  local time_start;
  local time_span;

  # Initialize variables
  local_path=$(readlink -f "${1}");
  time_start=$(date +%s);

  # FTP Uploads Credentials
  if ! __shtools_credentials_ftp "${variant}"; then
    >&2 echo '';
    >&2 echo ' syncftp: Open android_uploads_ftp.rc to see how to set your logins';
    >&2 echo '';
    return;
  fi;

  # Upload header
  echo '';
  echo -e " \e[1;33m[ Syncing with the server - User '${FTPUploadUserName}' ]\e[0m";
  echo '';

  # Path prepend
  if [ ! -z "${FTPUploadPath}" ] && [ ! -z "${remote_path}" ]; then
    remote_path=${FTPUploadPath}/${remote_path};
  fi;

  # Sync local to remote target
  if [ "${mode}" = '--upload' ]; then

    # Notify the folder name
    echo "   Syncing local '${local_path}' to remote '${remote_path}'...";
    echo '';

    # Sync through FTP
    if ! lftp \
        "ftp://${FTPUploadUserName}:${FTPUploadPassword}@${FTPUploadUserUrl}" \
         -e "mirror -e -R '${local_path}' '${remote_path}'; quit;"; then

      # Failed FTP sync
      notify-send 'Failed syncing through FTP...' 2> /dev/null;
      echo '';
      echo '   Failed syncing through FTP.';
    fi;

  # Sync remote to local target
  elif [ "${mode}" = '--download' ]; then

    # Notify the folder name
    echo "   Syncing remote '${remote_path}' to local '${local_path}'...";
    echo '';

    # Sync through FTP
    if ! lftp \
         "ftp://${FTPUploadUserName}:${FTPUploadPassword}@${FTPUploadUserUrl}" \
         -e "mirror -e '${remote_path}' '${local_path}'; quit;"; then

      # Failed FTP sync
      notify-send 'Failed syncing through FTP...' 2> /dev/null;
      echo '';
      echo '   Failed syncing through FTP.';
    fi;

  fi;

  # Show sync time
  time_span=$(($(date +%s) - time_start));
  echo -e " \e[1;37m[ Syncing done in ${time_span} secs ]\e[0m";
  echo '';
}
